package com.littlepay.kr4.paulin.dfeba77.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.florent37.materialviewpager.header.MaterialViewPagerHeaderDecorator;
import com.littlepay.kr4.paulin.dfeba77.MainActivity;
import com.littlepay.kr4.paulin.dfeba77.R;
import com.littlepay.kr4.paulin.dfeba77.adapter.TestRecyclerViewAdapter;
import com.littlepay.kr4.paulin.dfeba77.config.SqliteConfig;
import com.littlepay.kr4.paulin.dfeba77.entity.Sticker;
import com.littlepay.kr4.paulin.dfeba77.utils.DateUtil;
import com.littlepay.kr4.paulin.dfeba77.utils.SqliteHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.crashlytics.android.beta.Beta.TAG;

/**
 * Created by florentchampigny on 24/04/15.
 */
public class RecyclerViewFragment extends Fragment {
    //在此处获取布局绑定ID会产生异常，应交给Activity处理
    public List<Sticker> items = new ArrayList<>();
    private static final boolean GRID_LAYOUT = false;
    //TODO:set the count of sticker
    public static final int ITEM_COUNT = 25;//(int)(Math.random()*25)
    private String todayDate = DateUtil.getTodayDate();

    @BindView(R.id.recyclerView) RecyclerView recyclerView;

    public static boolean isLoadingMore = false;
    RecyclerView.LayoutManager mLayoutManager;
    private static String lastDate = "";

    public TestRecyclerViewAdapter getRecyclerViewAdapter() {
        return recyclerViewAdapter;
    }

    public TestRecyclerViewAdapter recyclerViewAdapter;

    /**
     * The RecyclerView is not currently scrolling.（静止没有滚动）
     */
    public static final int SCROLL_STATE_IDLE = 0;

    /**
     * The RecyclerView is currently being dragged by outside input such as user touch input.
     *（正在被外部拖拽,一般为用户正在用手指滚动）
     */
    public static final int SCROLL_STATE_DRAGGING = 1;

    /**
     * The RecyclerView is currently animating to a final position while not under outside control.
     *（自动滚动）
     */
    public static final int SCROLL_STATE_SETTLING = 2;

    public static RecyclerViewFragment newInstance() {
        return new RecyclerViewFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recyclerview, container, false);


    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //fabLayout = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(R.layout.activity_main,null).findViewById(R.id.fab_layout);

        ButterKnife.bind(this, view);



//        for (int i = 0; i < ITEM_COUNT; ++i) {
//            Sticker stickerItem = new Sticker();
//            stickerItem.cost = i;
//            //TestData.prices[(int)(Math.random()*TestData.prices.length)] ;
//            stickerItem.attribution = TestData.usages[(int)(Math.random()*TestData.usages.length)] ;
//            stickerItem.date = TestData.date[i/5];
//            //stickerItem.usage = TestData.usages[0];
//            //Log.i("sticker", "stickerInfo:" + stickerItem.toString()+"\n");
//            //System.out.println(stickerItem.toString());
//            items.add(stickerItem);
//        }


        //setup materialviewpager

        if (GRID_LAYOUT) {
            recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        } else {
            recyclerView.setLayoutManager(mLayoutManager = new LinearLayoutManager(getActivity()));
        }
        recyclerView.setHasFixedSize(true);
        recyclerView.setTop(1);
        //Use this now
        recyclerView.addItemDecoration(new MaterialViewPagerHeaderDecorator());
        recyclerView.setAdapter(recyclerViewAdapter = new TestRecyclerViewAdapter(getActivity(),
                new SqliteHelper(getContext() , SqliteConfig.SQLITE_DATABASE_FILE_NAME , null ,1).queryDataListByDay(null)));

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == SCROLL_STATE_IDLE){
                    //TODO：滚到尽头马上就会马上出现，如何解决，用Handler延时打开即可,并且判断是否在显示模式下
                    if(MainActivity.isdisplay){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                MainActivity.fabMenu.setVisibility(View.VISIBLE);
                            }
                        },750);
                    }
                }else{
                    if( MainActivity.fabMenu.isExpanded()){
                        MainActivity.fabMenu.collapse();
                    }
                    MainActivity.fabMenu.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //实现滑动到最下item前x个位置时加载更多的功能
                int lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                int totalItemCount = mLayoutManager.getItemCount();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy>0 表示向下滑动
                if (lastVisibleItem >= totalItemCount - 1 && dy > 0) {
                    if (isLoadingMore) {
                        Log.d(TAG, "ignore manually update!");
                    } else {
                        if(SqliteHelper.minID > 1){
                            isLoadingMore = true;
                            loadMore();//这里多线程也要手动控制isLoadingMore
                            Log.d(TAG, "Automatically update!");
                        }else {
                            //TODO：控制规定时间只显示一次
                            //Toast.makeText(getContext(),"没有更多记录了",Toast.LENGTH_SHORT).show();
                        }

                    }
                }
            }
        });
//        recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
//            @Override
//            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
//                return false;
//            }
//
//            @Override
//            public void onTouchEvent(RecyclerView rv, MotionEvent e) {
//                Toast.makeText(getActivity(),"长按！！！",Toast.LENGTH_SHORT).show();
//                new GestureDetector.SimpleOnGestureListener(){
//                    @Override
//                    public void onLongPress(MotionEvent e) {
//                        Toast.makeText(getActivity(),"长按！！！",Toast.LENGTH_SHORT).show();
//                    }
//                };
//            }
//
//            @Override
//            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
//
//            }
//        });
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                Log.d(TAG,"ignore manually update!");
//            }
//        });

    }
    //TODO:正确处理加载问题
    //已发现问题：新线程执行的话会造成正在adapter正在计算过程时又添加数据。
    //java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{e210b29 position=29 id=-1, oldPos=28, pLpos:28 scrap [attachedScrap] tmpDetached no parent}
    private void  loadMore(){
        SqliteHelper sqliteHelper = new SqliteHelper(getActivity() , SqliteConfig.SQLITE_DATABASE_FILE_NAME , null ,1);
        MainActivity.recyclerViewFragment.getRecyclerViewAdapter().insertMoreItem(sqliteHelper.queryDataListByDay(DateUtil.getPreviousDate(todayDate)));
        //日期往前算一天
        todayDate = DateUtil.getPreviousDate(todayDate);
        //isLoadingMore = true;//线程操作完成，回到准备拉取状态
    }
/*    public void InsertItem(Sticker sticker){
        items.add(sticker);
        recyclerView.getAdapter().notifyItemInserted(1);

    }*/

}
